from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql.cursors
from collections import Counter
import re
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

connection = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    database='testbase',
    cursorclass=pymysql.cursors.DictCursor
)
cursor = connection.cursor()


@app.route('/Ckaifa')
def Ckaifa():
    type_param = request.args.get('type', default=1, type=int)
    sql = "SELECT * FROM salary WHERE type = %s"
    cursor.execute(sql, (type_param,))
    result = cursor.fetchall()
    return jsonify(result)


@app.route('/Ctubiao')
def Ctubiao():
    sql = "SELECT skills FROM salary WHERE type = 1"
    cursor.execute(sql)
    result = cursor.fetchall()

    infos = []
    for item in result:
        infos += (item["skills"].replace(" ", "").split("\n"))

    infos = Counter(infos)
    infos = infos.most_common()

    X = []
    Y = []
    for item in infos:
        if item[0]:
            X.append(item[0])
            Y.append(item[1])

    return jsonify([X[:10], Y[:10]])

@app.route("/getjavabingtu")
def getjavabingtu():
    sql = "select education from salary where type=2"
    cursor.execute(sql)
    result = cursor.fetchall()
    connection.commit()
    infos=[]
    for item in result:
        if item["education"].replace(" ","").replace("\n",""):
            infos.append(item["education"].replace(" ","").replace("\n",""))
    infos=(Counter(infos).most_common())
    print(infos)
    arr=[]
    for item in infos:
        obj={}
        obj["value"]=item[1]
        obj["name"]=item[0]
        arr.append(obj)
    return arr
@app.route("/getphthonzhexian")
def getphthonzhexian():
    sql = "select education,salary from salary where type=3"
    cursor.execute(sql)
    result = cursor.fetchall()
    connection.commit()

    total = {}
    totalnum = {}
    for item in result:
        if item["education"]:
            edu = item["education"].replace(" ", "").replace("\n", "")
            price = item["salary"].replace(" ", "").replace("\n", "")

            if not (re.findall("天", price)) and re.findall("(千|万)", price):
                nums = re.findall("\d+\.{0,1}\d*", price)
                flag = re.findall("(千|万)", price)
                num1 = float(nums[0]) * 1000 if flag[0] == "千" else float(nums[0]) * 10000
                num2 = float(nums[1]) * 1000 if flag[1] == "千" else float(nums[1]) * 10000
                avg = (num1 + num2) / 2
                if total.get(edu):
                    total[edu] += avg
                    totalnum[edu] += 1
                else:
                    total[edu] = avg
                    totalnum[edu] = 1

    X = []
    Y = []
    for item in total:
        X.append(item)
        Y.append(total[item] / totalnum[item])

    print(X)
    print(Y)
    return [X, Y]
@app.route("/getSkillScore")
def getSkillScore():
    sql = "select skills from salary where type=1"
    cursor.execute(sql)
    result = cursor.fetchall()
    connection.commit()

    infos = []
    for item in result:
        infos += (item["skills"].replace(" ", "").split("\n"))

    infos = (Counter(infos))
    infos = infos.most_common()
    total=0
    newinfos=[]
    for item in infos:
        if item[0]:
            total+=item[1]
            newinfos.append(list(item))
    for item in newinfos:
        item[1]=item[1]/total
    return newinfos

@app.route("/predict")
def predict():
    X=[]
    city=float(request.args.get("city"))
    workage=float(request.args.get("workage"))
    education=float(request.args.get("education"))
    skills=request.args.get("skills")
    nums=0
    for item in skills.split(","):
        nums+=float(item)

    X.append(1)
    X.append(city)
    X.append(education)
    X.append(workage)
    X.append(nums)
    from theta import theta
    import numpy as np
    X=np.array(X)
    theta=np.array(theta)
    return str(X.dot(theta))
if __name__ == '__main__':
    app.run()
